package com.beemans.common.app.ui.fragments

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.beemans.common.app.R
import com.beemans.common.app.databinding.FragmentCountdownBinding
import com.beemans.common.app.ui.base.BaseFragment
import com.beemans.common.ext.setPageBack
import com.beemans.common.utils.CountDownTimer
import com.tiamosu.databinding.delegate.lazyDataBindingOrNull
import com.tiamosu.databinding.page.DataBindingConfig

/**
 * @author tiamosu
 * @date 2021/5/28.
 */
class CountdownFragment : BaseFragment() {
    private val dataBinding: FragmentCountdownBinding? by lazyDataBindingOrNull { }

    private var countDownTimer: CountDownTimer? = null
    private var title: String? = null

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_countdown)
    }

    override fun initParameters(bundle: Bundle?) {
        title = getString(MainFragment.PARAM_TITLE)
    }

    override fun initView(rootView: View?) {
        dataBinding?.countdownTitleBar?.setTvTitle { text = title }
    }

    override fun initEvent() {
        dataBinding?.countdownTitleBar?.setPageBack()
    }

    override fun onFlyLazyInitView() {
        super.onFlyLazyInitView()
        startCountDown()
    }

    /**
     * 开始执行倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountDown() {
        if (countDownTimer == null) {
            countDownTimer = CountDownTimer()
        }
        countDownTimer?.apply {
            setCountTime(70)
            start {
                onStart {
//                    Log.e("susu", "onStart")
                }
                onTick { sec ->
//                    Log.e("susu", "onTick:${format(sec)}")
                    dataBinding?.countdownTvTime?.text =
                        "${format(sec, isHms = true)}   ${format(sec)}"
                }
                onFinish {
                    clearTimer()
//                    Log.e("susu", "onFinish")
                }
            }
        }
    }

    override fun doBusiness() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        countDownTimer?.clearTimer()
    }
}